package com.example.pingmiantutui.ui.mistake_collection

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.example.pingmiantutui.R
import com.example.pingmiantutui.data.MistakeQuestion
import com.example.pingmiantutui.databinding.FragmentMistakeCollectionBinding
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup

class MistakeCollectionFragment : Fragment() {

    private var _binding: FragmentMistakeCollectionBinding? = null
    private val binding get() = _binding!!
    private var questions: List<MistakeQuestion> = emptyList()
    private var currentQuestionId = 1

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentMistakeCollectionBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 准备数据
        questions = listOf(
            MistakeQuestion(
                id = 1,
                description = "内外结构，外部图形轴对称，内部图形中心对称",
                errorprone = null,
                imagePath = "a1_item",
                typeTags = listOf("内外结构", "对称", "五推一")
            ),
            MistakeQuestion(
                id = 2,
                description1 = "中心对称—轴对称—中心对称+轴对称",
                description2 = "1条对称轴—2条对称轴—4条对称轴",
                errorprone2 = "容易看完前两幅图以为是对称",
                imagePath = "a2_item",
                typeTags = listOf("三三推一", "对称"),
                similarity = "三三推一+明显对称",
                difference = null,
                isContrastQuestion = true
            ),
            MistakeQuestion(
                id = 3,
                description = "轴对称—轴对称+中心对称，交错",
                errorprone = null,
                imagePath = "a3_item",
                analyseImagePath = "a3_analyse",
                typeTags = listOf("五推一", "对称", "ABAB"),
                isAnalyseQuestion = true
            ),
            MistakeQuestion(
                id = 4,
                description = null,
                errorprone = "不要看见圆多就一定选带圆的",
                imagePath = "a4_item",
                typeTags = listOf("五推一", "对称")
            )
        )

        // 设置导航按钮
        binding.prevButton.setOnClickListener { navigateToPrevious() }
        binding.nextButton.setOnClickListener { navigateToNext() }

        // 加载第一题
        loadQuestion(currentQuestionId)
    }

    private fun loadQuestion(questionId: Int) {
        val question = questions.find { it.id == questionId }
        if (question != null) {
            binding.questionContainer.removeAllViews()

            val questionView = when {
                question.isAnalyseQuestion -> {
                    LayoutInflater.from(requireContext()).inflate(R.layout.item_analyse_question, binding.questionContainer, false)
                }
                question.isContrastQuestion -> {
                    LayoutInflater.from(requireContext()).inflate(R.layout.item_contrast_question, binding.questionContainer, false)
                }
                else -> {
                    LayoutInflater.from(requireContext()).inflate(R.layout.item_single_question, binding.questionContainer, false)
                }
            }

            binding.questionContainer.addView(questionView)

            when {
                question.isAnalyseQuestion -> AnalyseQuestionViewHolder(questionView).bind(question, this)
                question.isContrastQuestion -> ContrastQuestionViewHolder(questionView).bind(question, this)
                else -> SingleQuestionViewHolder(questionView).bind(question, this)
            }
        }
    }

    private fun navigateToPrevious() {
        currentQuestionId = if (currentQuestionId > 1) {
            currentQuestionId - 1
        } else {
            questions.maxOf { it.id }
        }
        loadQuestion(currentQuestionId)
    }

    private fun navigateToNext() {
        currentQuestionId = if (currentQuestionId < questions.maxOf { it.id }) {
            currentQuestionId + 1
        } else {
            1
        }
        loadQuestion(currentQuestionId)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    class SingleQuestionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val imageView: ImageView = itemView.findViewById(R.id.questionImage)
        private val descriptionLabel: TextView = itemView.findViewById(R.id.descriptionLabel)
        private val descriptionView: TextView = itemView.findViewById(R.id.description)
        private val errorproneLabel: TextView = itemView.findViewById(R.id.errorproneLabel)
        private val errorproneView: TextView = itemView.findViewById(R.id.errorprone)
        private val typeTagsGroup: ChipGroup = itemView.findViewById(R.id.typeTagsGroup)

        fun bind(question: MistakeQuestion, fragment: MistakeCollectionFragment) {
            // 设置图片
            val imageResourceId = itemView.context.resources.getIdentifier(
                question.imagePath,
                "drawable",
                itemView.context.packageName
            )
            imageView.setImageResource(if (imageResourceId != 0) imageResourceId else R.drawable.ic_menu_camera)

            // 设置描述和易错点
            fragment.setTextViewVisibility(descriptionLabel, descriptionView, question.description)
            fragment.setTextViewVisibility(errorproneLabel, errorproneView, question.errorprone)

            // 设置题型标签
            fragment.setupTypeTags(typeTagsGroup, question.typeTags)
        }
    }

    class ContrastQuestionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val imageView: ImageView = itemView.findViewById(R.id.questionImage)
        private val errorproneLabel: TextView = itemView.findViewById(R.id.errorproneLabel)
        private val errorproneView: TextView = itemView.findViewById(R.id.errorprone)
        private val question1Label: TextView = itemView.findViewById(R.id.question1Label)
        private val description1View: TextView = itemView.findViewById(R.id.questionDescription1)
        private val errorprone1Label: TextView = itemView.findViewById(R.id.errorprone1Label)
        private val errorprone1View: TextView = itemView.findViewById(R.id.errorprone1)
        private val question2Label: TextView = itemView.findViewById(R.id.question2Label)
        private val description2View: TextView = itemView.findViewById(R.id.questionDescription2)
        private val errorprone2Label: TextView = itemView.findViewById(R.id.errorprone2Label)
        private val errorprone2View: TextView = itemView.findViewById(R.id.errorprone2)
        private val similarityLabel: TextView = itemView.findViewById(R.id.similarityLabel)
        private val similarityView: TextView = itemView.findViewById(R.id.similarity)
        private val differenceLabel: TextView = itemView.findViewById(R.id.differenceLabel)
        private val differenceView: TextView = itemView.findViewById(R.id.difference)
        private val typeTagsGroup: ChipGroup = itemView.findViewById(R.id.typeTagsGroup)

        fun bind(question: MistakeQuestion, fragment: MistakeCollectionFragment) {
            // 设置图片
            val imageResourceId = itemView.context.resources.getIdentifier(
                question.imagePath,
                "drawable",
                itemView.context.packageName
            )
            imageView.setImageResource(if (imageResourceId != 0) imageResourceId else R.drawable.ic_menu_camera)

            // 设置题目内容
            fragment.setTextViewVisibility(errorproneLabel, errorproneView, question.errorprone)
            fragment.setTextViewVisibility(question1Label, description1View, question.description1)
            fragment.setTextViewVisibility(errorprone1Label, errorprone1View, question.errorprone1)
            fragment.setTextViewVisibility(question2Label, description2View, question.description2)
            fragment.setTextViewVisibility(errorprone2Label, errorprone2View, question.errorprone2)
            fragment.setTextViewVisibility(similarityLabel, similarityView, question.similarity)
            fragment.setTextViewVisibility(differenceLabel, differenceView, question.difference)

            // 设置题型标签
            fragment.setupTypeTags(typeTagsGroup, question.typeTags)
        }
    }

    class AnalyseQuestionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val imageView: ImageView = itemView.findViewById(R.id.questionImage)
        private val descriptionLabel: TextView = itemView.findViewById(R.id.descriptionLabel)
        private val descriptionView: TextView = itemView.findViewById(R.id.description)
        private val errorproneLabel: TextView = itemView.findViewById(R.id.errorproneLabel)
        private val errorproneView: TextView = itemView.findViewById(R.id.errorprone)
        private val analyseLabel: TextView = itemView.findViewById(R.id.analyseLabel)
        private val analyseImage: ImageView = itemView.findViewById(R.id.analyseImage)
        private val typeTagsGroup: ChipGroup = itemView.findViewById(R.id.typeTagsGroup)

        fun bind(question: MistakeQuestion, fragment: MistakeCollectionFragment) {
            // 设置题目图片
            val imageResourceId = itemView.context.resources.getIdentifier(
                question.imagePath,
                "drawable",
                itemView.context.packageName
            )
            imageView.setImageResource(if (imageResourceId != 0) imageResourceId else R.drawable.ic_menu_camera)

            // 设置描述和易错点
            fragment.setTextViewVisibility(descriptionLabel, descriptionView, question.description)
            fragment.setTextViewVisibility(errorproneLabel, errorproneView, question.errorprone)

            // 设置解析图
            if (!question.analyseImagePath.isNullOrEmpty()) {
                try {
                    val analyseImageResourceId = itemView.context.resources.getIdentifier(
                        question.analyseImagePath,
                        "drawable",
                        itemView.context.packageName
                    )
                    if (analyseImageResourceId != 0) {
                        analyseLabel.visibility = View.VISIBLE
                        analyseImage.apply {
                            setImageResource(analyseImageResourceId)
                            visibility = View.VISIBLE
                        }
                    } else {
                        analyseLabel.visibility = View.GONE
                        analyseImage.visibility = View.GONE
                    }
                } catch (e: Exception) {
                    analyseLabel.visibility = View.GONE
                    analyseImage.visibility = View.GONE
                }
            } else {
                analyseLabel.visibility = View.GONE
                analyseImage.visibility = View.GONE
            }

            // 设置题型标签
            fragment.setupTypeTags(typeTagsGroup, question.typeTags)
        }
    }

    private fun setTextViewVisibility(label: TextView, content: TextView, text: String?) {
        if (!text.isNullOrEmpty()) {
            label.visibility = View.VISIBLE
            content.visibility = View.VISIBLE
            content.text = text
        } else {
            label.visibility = View.GONE
            content.visibility = View.GONE
        }
    }

    private fun setupTypeTags(group: ChipGroup, tags: List<String>) {
        group.removeAllViews()
        tags.forEach { tag ->
            val chip = Chip(group.context).apply {
                text = tag
                isCheckable = false
            }
            group.addView(chip)
        }
    }
}